# encoding = utf-8
class CartsController < ApplicationController

  before_filter :authenticate_user!

  def add
    product = Product.find(params[:id])
    if product.nil?
      flash[:error] = '您订购的产品不存在'
      redirect_to '/home'
      return
    elsif product.stock==0
      flash[:error] = "#{product.name}已经卖完啦！"
      redirect_to '/home'
      return
    else
      cart = current_user.carts.where(:product_id => product.id).first
      if cart.blank?
        cart = Cart.new({
            :user_id => current_user.id,
            :product_id => params[:id]
          })
      end
      
      if cart.save
        flash[:success] = "您已经把 #{product.name} 加入了购物车"
        redirect_to :action => 'show'
      else
        flash[:error] = '靠，加入购物车的时候居然失败了！~'
        redirect_to '/home'
      end

    end
  end

  def number
    product = Product.find(params[:product_id])
    if product.nil?
      flash[:error] = '您订购的产品不存在'
      redirect_to '/home'
      return
    elsif product.stock==0
      flash[:error] = "#{product.name}已经卖完啦！"
      redirect_to '/home'
      return
    else
      cart = current_user.carts.where(:product_id => product.id).first
      if cart.blank?
        flash[:error] = '你是怎么进来的？'
        redirect_to '/home'
      else
        if params[:number].to_i < 0
          flash[:error] = "晕，要账的来了！~"
          redirect_to :action => 'show'
          return
        end

        if params[:number].to_i == 0
          flash[:error] = "不要了？点击右边的删除"
          redirect_to :action => 'show'
          return
        end
        
        if product.stock >= params[:number].to_i
          cart.number = params[:number].to_i
        else
          flash[:error] = "没你要的那么多了，#{product.name}一共还有#{product.stock}份"
          redirect_to :action => 'show'
          return
        end
      end

      if cart.save
        flash[:success] = "您已经成功更改了购物车中#{product.name}的数量"
      else
        flash[:error] = '保存数量的时候出错了，再试试吧'
      end
      redirect_to :action => 'show'
    end
  end
  
  def show
    @carts = current_user.carts
  end

  def delete
    cart = current_user.carts.find(params[:id])
    if !cart.nil?
      cart.destroy
      flash[:success] = "您已经把 #{cart.product.name} 清出了购物车"
    end
    redirect_to :action => 'show'
  end
end
